package com.chen.codesandbox.controller;

import com.chen.codesandbox.codeSandbox.*;
import com.chen.codesandbox.model.ExecuteCodeRequest;
import com.chen.codesandbox.model.ExecuteCodeResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestController("/")
public class MainController {

    // 定义鉴权请求头和密钥
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";

    @Autowired
    JavaDockerCodeSandbox javaDockerCodeSandbox;

    @Autowired
    CDockerCodeSandbox cDockerCodeSandbox;

    @Autowired
    CPPDockerCodeSandbox cppDockerCodeSandbox;

    @Autowired
    PythonDockerCodeSandbox pythonDockerCodeSandbox;

    /**
     * 执行代码
     *
     * @param executeCodeRequest
     * @return
     */
    @PostMapping("/executeCode")
    ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("executeCodeRequest:" + executeCodeRequest);
        // 基本的认证
        String authHeader = request.getHeader(AUTH_REQUEST_HEADER);
        if (!AUTH_REQUEST_SECRET.equals(authHeader)) {
            response.setStatus(403);
            return null;
        }
        if (executeCodeRequest == null) {
            throw new RuntimeException("请求参数为空");
        }
        String language = executeCodeRequest.getLanguage();
        ExecuteCodeResponse executeCodeResponse = null;
        if ("C".equals(language)) {
            executeCodeResponse = cDockerCodeSandbox.executeCode(executeCodeRequest);
        } else if ("Java".equals(language)) {
            executeCodeResponse = javaDockerCodeSandbox.executeCode(executeCodeRequest);
        } else if ("C++".equals(language)) {
            executeCodeResponse = cppDockerCodeSandbox.executeCode(executeCodeRequest);
        } else if ("Python".equals(language)) {
            executeCodeResponse = pythonDockerCodeSandbox.executeCode(executeCodeRequest);
        }
        System.out.println("返回信息");
        System.out.println(executeCodeResponse);
        return executeCodeResponse;
    }
}
